import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';

import { getPSITokenId } from '../../../utils/tokenId';

import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';

import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';

import LeftArrowIcon from '@material-ui/icons/KeyboardArrowLeft'
import EditIcon from '@material-ui/icons/Edit'

import Grid from '@material-ui/core/Grid';
import CssBaseline from '@material-ui/core/CssBaseline';
import { MuiThemeProvider } from '@material-ui/core/styles';
import mainTheme from '../../../theme/mainTheme';
import LinearProgress from '@material-ui/core/LinearProgress';
import MenuIcon from '@material-ui/icons/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Menu from '@material-ui/core/Menu';

import styles from '../../../utils/pageLayout';

import CategoryEditDialog from '../components/CategoryEditDialog';

class CustomerCategoryListPage extends React.Component {
  state = {
    add: false,
    createDialogOpen: false,
    anchorEl: null,
  }

  constructor(props) {
    super(props);

    if (!getPSITokenId()) {
      router.replace('/auth/login');
    }
  }

  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'customerCategoryList/queryCategoryList', payload: {} });
  }

  handleMenu = event => {
    this.setState({ anchorEl: event.currentTarget });
  };

  onAddCategory = () => {
    const { dispatch } = this.props;
    const entity = { id: '', code: '', name: '', psId: '', psName: '' };
    dispatch({ type: 'customerCategoryList/saveEntity', payload: { entity } });

    this.setState({
      anchorEl: null, createDialogOpen: true,
      add: true
    });
  }

  onEditCategory = (event) => {
    const { dispatch } = this.props;

    const categoryId = event.currentTarget.getAttribute('data-id')

    dispatch({ type: 'customerCategoryList/queryCustomerCategory', payload: { categoryId } });

    this.setState({ createDialogOpen: true, add: false });
  }

  render() {
    const { classes, list, loading, entity } = this.props;
    const { add, createDialogOpen, anchorEl } = this.state;

    return (
      <MuiThemeProvider theme={mainTheme}>
        <CssBaseline />
        <Grid container alignItems='flex-start' wrap='nowrap' direction='column' className={classes.r}>
          <Grid item className={classes.h}>
            <AppBar position='static'>
              <Toolbar>
                <IconButton className={classes.menuButton} onClick={() => { router.goBack() }}>
                  <LeftArrowIcon color='inherit' />
                </IconButton>
                <Typography style={{ flex: 1 }} variant="title" color="inherit">
                  客户分类
                </Typography>
                <IconButton onClick={this.handleMenu}>
                  <MenuIcon color='inherit' />
                </IconButton>
                <Menu
                  anchorEl={anchorEl}
                  anchorOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  transformOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  open={anchorEl !== null}
                  onClose={() => { this.setState({ anchorEl: null }) }}>
                  <MenuItem onClick={this.onAddCategory}>新增客户分类</MenuItem>
                </Menu>
              </Toolbar>
            </AppBar>
            <LinearProgress color='secondary' hidden={!loading} />
          </Grid>

          <Grid item className={classes.c}>
            <List>
              {
                list && list.map((it, index) => {
                  return <ListItem key={index} divider>
                    <ListItemText primary={it.name}
                      secondary={`编码: ${it.code}` + (it.psName ? ` / 价格体系: ${it.psName}` : '') + ` / 客户数: ${it.cnt}`}>
                    </ListItemText>
                    <ListItemSecondaryAction>
                      <IconButton data-id={it.id} onClick={this.onEditCategory}>
                        <EditIcon />
                      </IconButton>
                    </ListItemSecondaryAction>
                  </ListItem>
                })
              }
              {
                (list && list.length === 0) && <ListItem key={0}>没有客户分类</ListItem>
              }
            </List>
          </Grid>
        </Grid>
        <CategoryEditDialog entity={entity} open={createDialogOpen}
          onOK={() => { this.setState({ createDialogOpen: false }) }}
          onCancel={() => { this.setState({ createDialogOpen: false }) }}
          add={add} />
      </MuiThemeProvider>
    );
  }
}

CustomerCategoryListPage.propTypes = {
};

function mapStateToProps(state) {
  const { list, entity } = state.customerCategoryList;

  return {
    list, loading: state.loading.models.customerCategoryList,
    entity
  };
}

// connect是DVA把Model和Component关联起来的方法
// mapStateToProps，也就是把Model里面的state赋值给Component的props
// 这样state改变的时候，组件的props值也改变，从而UI展现的数据也变化
// this.props.dispatch会自动被DVA注入
// 通过this.props.dispatch就可以调用DVA Model里面的action
export default connect(mapStateToProps)(withStyles(styles)(CustomerCategoryListPage));
